package com.schoolComments.service.impl;

import cn.hutool.json.JSONUtil;
import com.schoolComments.dto.Result;
import com.schoolComments.entity.ShopType;
import com.schoolComments.mapper.ShopTypeMapper;
import com.schoolComments.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    ShopTypeMapper shopTypeMapper;
    @Override
    public Result queryAllShopType() {
        //去redis中查询
        Long size = stringRedisTemplate.opsForList().size("cache:shopType:");
        //有则返回数据
        if (size != null && size != 0) {
            //把Json的list 转换为 对象的list
            List<String> shopTypesStr = stringRedisTemplate.opsForList().range("cache:shopType:", 0, size - 1);
            List<ShopType> shopTypes = new ArrayList<>();
            for (String shopTypeStr : shopTypesStr) {
                ShopType shopType = JSONUtil.toBean(shopTypeStr, ShopType.class);
                shopTypes.add(shopType);
            }
            return Result.ok(shopTypes);
        }
        //没有则去数据库中查询
        List<ShopType> shopTypes = shopTypeMapper.queryAll();
        //查询不到则报错
        if (shopTypes == null) {
            return Result.fail("没有种类相关的信息");
        }
        //查询到则写入redis
        //将对象list转为Json list
        List<String> strings = new ArrayList<>();
        for (ShopType shopType : shopTypes) {
            String s = JSONUtil.toJsonStr(shopType);
            strings.add(s);
        }
        stringRedisTemplate.opsForList().rightPushAll("cache:shopType:", strings);
        //返回数据
        return Result.ok(shopTypes);
    }
}